import { getUserList } from '@/api/user'
import { getWithExpires, setWithExpires } from '@/libs/storage'

export default {
  namespaced: true,
  state: {
    info: {},
    allUsers: [],
    workUsers: [],
  },
  actions: {
    init({ state }) {
      return new Promise(async (resolve) => {
        const url = '/user/partnerListV2'
        let allUserRecords = getWithExpires(url)
        if (!allUserRecords) {
          const response = await getUserList({
            pageNum: 1,
            pageSize: 2000
          })
          allUserRecords = response.records || []
          setWithExpires(url, allUserRecords)
        }
        
        const allUsers = allUserRecords.map(u => ({
          ...u, key: u.userId,
          roleCodeList: u.roleCodeList || []
        }));
        const workUsers = allUsers.filter(u => u.status === 0);

        state.allUsers = allUsers
        state.workUsers = workUsers
        resolve()
      });
    },
    set({ state, dispatch }, info) {
      return new Promise(async resolve => {
        // store 赋值
        state.info = info;
        // 持久化
        await dispatch('admin/db/set', {
          dbName: 'sys',
          path: 'user.info',
          value: info,
          user: true
        }, { root: true });
        // end
        resolve();
      })
    },
    load({ state, dispatch }) {
      return new Promise(async resolve => {
        // store 赋值
        state.info = await dispatch('admin/db/get', {
          dbName: 'sys',
          path: 'user.info',
          defaultValue: {},
          user: true
        }, { root: true });
        // end
        resolve();
      })
    }
  }
}
